package com.aboverock.module.system.service.impl;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aboverock.module.system.domain.Log;
import com.aboverock.module.system.domain.StatisticalResult;
import com.aboverock.module.system.enums.StatisticalUnit;
import com.aboverock.module.system.mapper.LogMapper;
import com.aboverock.module.system.service.LogService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Rock Wang
 * @since 2018-10-30
 */
@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService {

    @Override
    public List<StatisticalResult> getUseStatisticalInfo(Long startTime, StatisticalUnit unit) {
        List<StatisticalResult> info = baseMapper.getUseStatisticalInfo(startTime, unit);
        Map<String, Integer> collect = info.stream()
                .collect(Collectors.toMap(StatisticalResult::getDate, StatisticalResult::getCount));
        
        Map<String, Integer> result = new HashMap<>(collect.size());
        LocalDate start = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault())
                .toLocalDate();
        LocalDate now = LocalDate.now();
        switch (unit) {
            case WEEK:
                return info;
            case MONTH:
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
                while (start.isBefore(now)) {
                    String date = formatter.format(start);
                    result.put(date, Optional.ofNullable(collect.get(date)).orElse(0));
                    start = start.plusMonths(1);
                }
                result.put(formatter.format(now),
                        Optional.ofNullable(collect.get(formatter.format(now))).orElse(0));
                break;
            case YEAR:
                formatter = DateTimeFormatter.ofPattern("yyyy");
                while (start.isBefore(now)) {
                    String date = formatter.format(start);
                    result.put(date, Optional.ofNullable(collect.get(date)).orElse(0));
                    start = start.plusYears(1);
                }
                result.put(formatter.format(now),
                        Optional.ofNullable(collect.get(formatter.format(now))).orElse(0));
            default:
                break;
        }
        
        return result.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey()))
                .map(e -> new StatisticalResult(e.getKey(), e.getValue()))
                .collect(Collectors.toList());
    }

}
